`include "timescale.v"

module apb(
	input 		   presetn,
	input 		   pclk,
	input 		   psel,
	input 		   penable,
	input 		   pwrite,
	input  [31:0]  paddr,
	input  [31:0]  pwdata,
	output [31:0]  prdata
	);

wire 	  [31:0]  BASE_ADDR;
assign 			  BASE_ADDR   = 32'h8001_0000;

// reg 	  [31:0]  rx_bd, tx_bd;
// reg 	  [31:0]  rx_bd, tx_bd;
reg 	  [31:0]  DMA_CTRL[0:7];				//8 words memory
// 0 : tx_bd
// 1 : rx_bd


//fsm of the write operation
localparam [1:0]  IDLE 		  = 2'b00,
				  SETUP = 2'b01,
				  ENABLE = 2'b11;

reg 	  [1:0]   currentState, nextState;
always@(*)
begin
  nextState = IDLE;
  case(currentState)
	  IDLE: begin
		if(psel & ~penable)
		  nextState = SETUP;
	  end
	  SETUP: begin
		if(psel & penable)
		  nextState = ENABLE;	//the next clk must go into this state
	  end
	  ENABLE: begin
		if(psel & ~penable)
		  nextState = SETUP;
	  end
  endcase
end


reg 	  [31:0]  waddr;
integer 		  i;
always@(posedge pclk or negedge presetn)
begin
  if(!presetn) begin
	currentState <= IDLE;
	for(i=0;i<8;i=i+1)
	  DMA_CTRL[i] <= 32'd0;
  end
  else begin
	currentState <= nextState;
	case(nextState)
		SETUP: begin
		  $display("paddr = %x", paddr);
		  waddr <= paddr;
		end
		ENABLE:
		  DMA_CTRL[waddr-BASE_ADDR] <= pwdata;
	endcase
  end
end

endmodule // apb


// always@(posedge pclk or negedge presetn)
// begin
//   if(!presetn) begin
// 	rx_bd <= 32'h0000_0000;				//the init value ??
// 	tx_bd <= 32'h0000_0000;
//   end
//   else 
// 	case(currentState)
// 		end
// end

